local util = require "util"
local conf = require "conf"
local require = require
local setmetatable = setmetatable
local error = error
local table = table
local ngx = ngx
local os = os
local string = string
local tonumber = tonumber
local pairs = pairs
package.cpath = "/usr/nginx/?.so;;"
local json = require 'cjson'
module(...)
_VERSION = '0.1'

function search(user, args)
    local page_no, page_size, id, order_id, serial_no, fid, create_time = tonumber(args.page_no), tonumber(args.page_size), args.id, args.order_id, args.serial_no, args.fid, args.create_time, args.eid
    local db = conf.get_mysql()
    local sql = "SELECT * FROM flight_log WHERE 1=1 ";

    if serial_no then
        sql = sql .. " AND serial_no like '%" .. serial_no .. "%'"
    end

    if order_id and tonumber(order_id) then
        sql = sql .. " AND `flight_log`.order_id = " .. tonumber(order_id)
    end

    if fid and tonumber(fid) then
        sql = sql .. " AND `flight_log`.fid = " .. tonumber(fid)
    end

    if id and tonumber(id) then
        sql = sql .. " AND `flight_log`.id = " .. tonumber(id)
    end

    if create_time then
        sql = sql .. " AND `flight_log`.create_time >= " .. tonumber(create_time)
    end

    -- sql = sql .. " ORDER BY `flight_log`.update_time DESC"
    
    local count = #(db:query(sql) or {})

    if page_no and page_size then
        sql = sql ..  " LIMIT " .. (page_no * page_size) .. "," .. page_size
    end
    ngx.log(ngx.ERR, sql)
    local res = db:query(sql)
    return res,count
end

function searchControler(user, args)
    local res, count = search(user, args)
    if not res then
        ngx.print(json.encode({
            err = 1,
            msg = '未找到相应的订单'
        }))
        ngx.exit(200)
    else
        ngx.print(json.encode({
            err = 0,
            msg = res,
            count = count
        }))
        ngx.exit(200)
    end
end



function default(args)
    if args.action == 'search' then
        local user = conf.parse_token(args)
        searchControler(user, args)
    end
end

local class_mt = {
    __newindex = function (table, key, val)
        error('attempt to write to undeclared variable "' .. key .. '"')
    end
}
setmetatable(_M, class_mt)
